<template>
  <el-card class="form-container" shadow="never">
    <el-form :model="coupon" :rules="rules" ref="formRef" label-width="100px" size="small">
      <el-form-item label="优惠券类型：">
        <el-select v-model="coupon.type">
          <el-option v-for="item in COUPON_TYPE_MAP" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="优惠券名称：" prop="name">
        <el-input v-model="coupon.name"></el-input>
      </el-form-item>
      <el-form-item label="适用平台：">
        <el-select v-model="coupon.platform">
          <el-option v-for="item in COUPON_RANGE_MAP" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="总发行量：" prop="publishCount">
        <el-input v-model.number="coupon.publishCount" placeholder="只能输入正整数"></el-input>
      </el-form-item>
      <el-form-item label="面额：" prop="amount">
        <el-input v-model.number="coupon.amount" placeholder="面值只能是数值，限2位小数">
          <template #append>元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="每人限领：">
        <el-input v-model="coupon.perLimit" placeholder="只能输入正整数">
          <template #append>张</template>
        </el-input>
      </el-form-item>
      <el-form-item label="使用门槛：" prop="minPoint">
        <el-input v-model.number="coupon.minPoint" placeholder="只能输入正整数">
          <template #prepend>满</template>
          <template #append>元可用</template>
        </el-input>
      </el-form-item>
      <el-form-item label="领取日期：" prop="enableTime">
        <el-date-picker style="width: 100%" type="date" placeholder="选择日期" v-model="coupon.enableTime"></el-date-picker>
      </el-form-item>
      <el-form-item label="有效期：">
        <el-date-picker type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" v-model="timeRange"></el-date-picker>
      </el-form-item>
      <el-form-item label="可使用商品：">
        <el-radio-group v-model="coupon.useType">
          <el-radio-button v-for="i in COUPON_AREA_MAP" :key="i.value" :value="i.value">{{ i.label }}</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-show="coupon.useType === 1">
        <el-cascader
          style="width: 100%"
          clearable
          placeholder="请选择分类名称"
          :props="{ label: 'name', value: 'id', multiple: true }"
          v-model="selectProductCate"
          :options="productCateOptions"
          @change="handleAddProductCategoryRelation"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item v-show="coupon.useType === 2">
        <el-select
          v-model="selectProduct"
          filterable
          remote
          reserve-keyword
          placeholder="商品名称/商品货号"
          :remote-method="searchProductMethod"
          :loading="selectProductLoading"
        >
          <el-option v-for="item in selectProductOptions" :key="item.id" :label="item.name" :value="item.id">
            <span style="float: left">{{ item.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">NO.{{ item.productSn }}</span>
          </el-option>
        </el-select>
        <el-button @click="handleAddProductRelation()">添加</el-button>
        <el-table ref="productRelationTable" :data="coupon.productRelationList" style="width: 100%; margin-top: 20px" border>
          <el-table-column label="商品名称" align="center">
            <template #default="scope">{{ scope.row.productName }}</template>
          </el-table-column>
          <el-table-column label="货号" align="center" width="120">
            <template #default="scope">NO.{{ scope.row.productSn }}</template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100">
            <template #default="scope">
              <el-button size="small" link @click="handleDeleteProductRelation(scope.$index)">删除 </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="备注：">
        <el-input type="textarea" :rows="5" placeholder="请输入内容" v-model="coupon.note"> </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button v-if="!route.query.id" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script setup lang="ts">
import { createCoupon, getCoupon, updateCoupon } from '@/api/coupon'
import { fetchSimpleList as fetchProductList } from '@/api/product'
import { fetchListWithChildren } from '@/api/productCate'
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, type FormInstance } from 'element-plus'
import { COUPON_RANGE_MAP, COUPON_TYPE_MAP, COUPON_AREA_MAP } from '@/constant'
import type { Product, ProductCategoryRelation } from '@/models/product'
import type { CouponDto } from '@/models/coupon'
import type { ProductCateTree } from '@/models/productCate'

defineOptions({ name: 'CouponDetail' })
const rules = {
  name: [
    { requird: true, message: '请输入优惠券名称', trigger: 'blur' },
    { min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur' },
  ],
  publishCount: [{ type: 'number', required: true, message: '只能输入正整数', trigger: 'blur' }],
  amount: [
    {
      type: 'number',
      required: true,
      message: '面值只能是数值，0.01-10000，限2位小数',
      trigger: 'blur',
    },
  ],
  minPoint: [{ type: 'number', required: true, message: '只能输入正整数', trigger: 'blur' }],
}
const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance>()
const coupon = ref<CouponDto>({ productRelationList: [], productCategoryRelationList: [] })
const selectProduct = ref<Product>({})
const selectProductLoading = ref(false)
const selectProductOptions = ref<Product[]>([])
const selectProductCate = ref<number[][]>([])
const productCateOptions = ref<ProductCateTree[]>([])
const timeRange = ref<string[]>([])
const loading = ref(false)
onMounted(async () => {
  if (route.query.id) {
    const response = await getCoupon(Number(route.query.id))
    const { startTime, endTime, ...data } = response.data.data
    timeRange.value = startTime && endTime ? [startTime, endTime] : []
    coupon.value = data
  }
  await getProductCateList()
  selectProductCate.value =
    coupon.value.productCategoryRelationList?.map((item) => {
      const parentId = productCateOptions.value.find((e) => e.children?.find((i) => i.id === item.productCategoryId))?.id as number
      return [parentId, item.productCategoryId as number]
    }) || []
})
async function onSubmit() {
  await formRef.value?.validate()
  const { ...params } = coupon.value
  const [startTime, endTime] = timeRange.value
  params.startTime = startTime
  params.endTime = endTime
  if (route.query.id) {
    await updateCoupon(params)
    ElMessage.success('修改成功')
  } else {
    await createCoupon(params)
    ElMessage.success('提交成功')
  }
  router.back()
  formRef.value?.resetFields()
}

function resetForm() {
  formRef.value?.resetFields()
  coupon.value = { productRelationList: [], productCategoryRelationList: [] }
}

async function searchProductMethod(query: string) {
  if (query !== '') {
    loading.value = true
    const response = await fetchProductList({ keyword: query })
    loading.value = false
    selectProductOptions.value = response.data.data
  } else {
    selectProductOptions.value = []
  }
}
function handleAddProductRelation() {
  if (selectProduct.value === null) {
    ElMessage.warning('请先选择商品')
    return
  }
  const product = selectProductOptions.value.find((item) => item.id === selectProduct.value)
  product && coupon.value.productRelationList?.push(product)
  selectProduct.value = {}
}
function handleDeleteProductRelation(index: number) {
  coupon.value.productRelationList?.splice(index, 1)
}
function handleAddProductCategoryRelation(row: number[][]) {
  coupon.value.productCategoryRelationList = row.map(getProductCateByIds) as ProductCategoryRelation[]
}
async function getProductCateList() {
  const response = await fetchListWithChildren()
  productCateOptions.value = response.data.data
}
function getProductCateByIds(ids: number[]) {
  const [parentId, childId] = ids
  const parent = productCateOptions.value.find((item) => item.id === parentId)
  if (!parent) return
  const child = parent.children?.find((i) => i?.id === childId)
  if (!child) return
  return { productCategoryId: childId, productCategoryName: child.name, id: parentId, parentCategoryName: parent.name }
}
</script>
<style scoped>
.input-width {
  width: 60%;
}
</style>
